// client/pages/preferences.js
import React, { useState, useContext, useEffect, useRef } from "react";
import getConfig from "next/config";
import { useRouter } from "next/router";
import { withAuthServerSideProps } from "../utils/withAuth";
import Box from "../components/Box";
import Text from "../components/Text";
import Input from "../components/Input";
import Button from "../components/Button";
// 导入原始Checkbox但不使用
// import Checkbox from "../components/Checkbox";
import SEO from "../components/SEO";
import LoadingContext from "../utils/LoadingContext";
import { NotificationContext } from "../components/Notifications";
import LocaleContext from "../utils/LocaleContext";

// 自定义Checkbox组件
const CustomCheckbox = ({ label, checked, onChange }) => {
  return (
    <div style={{ display: "flex", alignItems: "center" }}>
      <input
        type="checkbox"
        checked={checked}
        onChange={onChange}
        id={`checkbox-${label}`}
        style={{ width: "16px", height: "16px" }}
      />
      <label
        htmlFor={`checkbox-${label}`}
        style={{ marginLeft: "8px", cursor: "pointer" }}
      >
        {label}
      </label>
    </div>
  );
};

function Preferences({ token, categories }) {
  const [preferences, setPreferences] = useState({
    categories: [],
    tags: [],
    languages: ["en"],
    quality: [],
  });

  const [tags, setTags] = useState("");
  const [loading, setLoading] = useState(false);
  const [initialLoading, setInitialLoading] = useState(true);
  const [forceUpdate, setForceUpdate] = useState(0);
  const preferencesLoaded = useRef(false);

  const { setLoading: setGlobalLoading } = useContext(LoadingContext);
  const { addNotification } = useContext(NotificationContext);
  const { getLocaleString } = useContext(LocaleContext);

  const router = useRouter();

  const {
    publicRuntimeConfig: { SQ_API_URL },
  } = getConfig();

  // 获取用户已有偏好
  useEffect(() => {
    const fetchUserPreferences = async () => {
      try {
        setInitialLoading(true);
        const response = await fetch(`${SQ_API_URL}/user/preferences`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        console.log("API Response:", response);

        if (response.ok) {
          const data = await response.json();
          console.log("Raw preference data:", data);

          if (data.explicitPreferences) {
            // 确保categories和quality是数组
            const parsedPreferences = {
              ...data.explicitPreferences,
              categories: data.explicitPreferences.categories || [],
              quality: data.explicitPreferences.quality || [],
              tags: data.explicitPreferences.tags || [],
              languages: data.explicitPreferences.languages || ["en"],
            };

            console.log("Processed preferences:", parsedPreferences);
            console.log(
              "Categories in preferences:",
              parsedPreferences.categories
            );

            setPreferences(parsedPreferences);
            preferencesLoaded.current = true;

            // 处理标签
            if (parsedPreferences.tags && parsedPreferences.tags.length > 0) {
              setTags(parsedPreferences.tags.join(", "));
            } else {
              setTags("");
            }

            // 强制组件更新以确保选中状态正确显示
            setTimeout(() => {
              setForceUpdate((prev) => prev + 1);
            }, 100);
          }
        }
      } catch (error) {
        console.error("获取用户偏好失败:", error);
        addNotification(
          "error",
          getLocaleString("preferences.fetchError") || "获取用户偏好失败"
        );
      } finally {
        setInitialLoading(false);
      }
    };

    if (token) {
      fetchUserPreferences();
    }
  }, [token]);

  // 增强的类别匹配函数
  const isCategorySelected = (category) => {
    // 使用不区分大小写的比较
    return preferences.categories.some(
      (cat) =>
        typeof cat === "string" && cat.toLowerCase() === category.toLowerCase()
    );
  };

  // 增强的质量匹配函数
  const isQualitySelected = (quality) => {
    return preferences.quality.some(
      (q) => typeof q === "string" && q.toLowerCase() === quality.toLowerCase()
    );
  };

  // 处理分类选择
  const handleCategoryChange = (category, checked) => {
    setPreferences((prev) => {
      console.log(`Changing category ${category} to ${checked}`);
      const newCategories = [...prev.categories];

      if (checked) {
        if (
          !newCategories.some(
            (cat) => cat.toLowerCase() === category.toLowerCase()
          )
        ) {
          newCategories.push(category);
        }
      } else {
        const index = newCategories.findIndex(
          (cat) => cat.toLowerCase() === category.toLowerCase()
        );
        if (index !== -1) {
          newCategories.splice(index, 1);
        }
      }

      console.log("New categories after change:", newCategories);
      return { ...prev, categories: newCategories };
    });
  };

  // 处理质量选择
  const handleQualityChange = (quality, checked) => {
    setPreferences((prev) => {
      console.log(`Changing quality ${quality} to ${checked}`);
      const newQuality = [...prev.quality];

      if (checked) {
        if (
          !newQuality.some((q) => q.toLowerCase() === quality.toLowerCase())
        ) {
          newQuality.push(quality);
        }
      } else {
        const index = newQuality.findIndex(
          (q) => q.toLowerCase() === quality.toLowerCase()
        );
        if (index !== -1) {
          newQuality.splice(index, 1);
        }
      }

      console.log("New quality after change:", newQuality);
      return { ...prev, quality: newQuality };
    });
  };

  // 处理提交
  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      setLoading(true);
      setGlobalLoading(true);

      // 处理标签
      const tagList = tags
        .split(",")
        .map((tag) => tag.trim())
        .filter((tag) => tag);

      console.log("提交偏好设置:", {
        preferences: {
          ...preferences,
          tags: tagList,
        },
      });

      const response = await fetch(`${SQ_API_URL}/recommendation/preferences`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          preferences: {
            ...preferences,
            tags: tagList,
          },
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || `保存失败: ${response.status}`);
      }

      addNotification(
        "success",
        getLocaleString("preferences.saveSuccess") || "偏好设置已保存"
      );

      // 跳转回首页
      //   router.push("/");
    } catch (error) {
      console.error("保存偏好失败:", error);
      addNotification(
        "error",
        `${getLocaleString("preferences.saveError") || "保存偏好设置失败"}: ${
          error.message
        }`
      );
    } finally {
      setLoading(false);
      setGlobalLoading(false);
    }
  };

  const qualityOptions = ["480p", "720p", "1080p", "2160p", "HDR", "SDR"];

  // 添加调试信息
  useEffect(() => {
    if (preferencesLoaded.current) {
      console.log("Available categories:", Object.keys(categories));
      console.log("Current preferences.categories:", preferences.categories);
      console.log("Current preferences.quality:", preferences.quality);

      // 打印每个类别是否应该被选中
      Object.keys(categories).forEach((category) => {
        console.log(
          `Should ${category} be checked:`,
          isCategorySelected(category)
        );
      });

      // 打印每个质量选项是否应该被选中
      qualityOptions.forEach((quality) => {
        console.log(
          `Should ${quality} be checked:`,
          isQualitySelected(quality)
        );
      });
    }
  }, [categories, preferences, forceUpdate, qualityOptions]);

  if (initialLoading) {
    return (
      <Box>
        <Text>{getLocaleString("common.loading") || "加载中..."}</Text>
      </Box>
    );
  }

  return (
    <>
      <SEO title={getLocaleString("preferences.title") || "偏好设置"} />
      <Text as="h1" mb={5}>
        {getLocaleString("preferences.title") || "偏好设置"}
      </Text>

      <Box as="form" onSubmit={handleSubmit}>
        <Box mb={5}>
          <Text as="h2" mb={3}>
            {getLocaleString("preferences.categories") || "分类偏好"}
          </Text>
          <Box display="flex" flexWrap="wrap">
            {Object.keys(categories).map((category) => {
              const isChecked = isCategorySelected(category);
              console.log(
                `Rendering category ${category}, checked:`,
                isChecked
              );
              return (
                <Box key={category} width="33%" mb={3}>
                  <CustomCheckbox
                    label={category}
                    checked={isChecked}
                    onChange={(e) =>
                      handleCategoryChange(category, e.target.checked)
                    }
                  />
                </Box>
              );
            })}
          </Box>
        </Box>

        <Box mb={5}>
          <Text as="h2" mb={3}>
            {getLocaleString("preferences.quality") || "画质偏好"}
          </Text>
          <Box display="flex" flexWrap="wrap">
            {qualityOptions.map((quality) => {
              const isChecked = isQualitySelected(quality);
              console.log(`Rendering quality ${quality}, checked:`, isChecked);
              return (
                <Box key={quality} width="33%" mb={3}>
                  <CustomCheckbox
                    label={quality}
                    checked={isChecked}
                    onChange={(e) =>
                      handleQualityChange(quality, e.target.checked)
                    }
                  />
                </Box>
              );
            })}
          </Box>
        </Box>

        <Box mb={5}>
          <Text as="h2" mb={3}>
            {getLocaleString("preferences.tags") || "标签偏好"}
          </Text>
          <Input
            value={tags}
            onChange={(e) => setTags(e.target.value)}
            placeholder={
              getLocaleString("preferences.tagsPlaceholder") ||
              "输入标签，用逗号分隔"
            }
          />
          <Text fontSize={1} color="grey" mt={2}>
            {getLocaleString("preferences.tagsHelp") ||
              "例如: 动作, 科幻, 冒险"}
          </Text>
        </Box>

        <Button disabled={loading}>
          {loading
            ? getLocaleString("common.saving") || "保存中..."
            : getLocaleString("preferences.save") || "保存偏好"}
        </Button>
      </Box>
    </>
  );
}

export const getServerSideProps = withAuthServerSideProps(async ({ token }) => {
  if (!token) return { redirect: { destination: "/login", permanent: false } };

  const {
    publicRuntimeConfig: { SQ_TORRENT_CATEGORIES },
  } = getConfig();

  return {
    props: {
      token,
      categories: SQ_TORRENT_CATEGORIES,
    },
  };
});

export default Preferences;
